#include<iostream>
#define rep(i,a,b) for(register int i=(a);i<=(b);i++)

using namespace std;

const int A=11111;

const int F=111;

int dis[F][F];

int a[A];

inline int min(int x,int y){return x<y?x:y;}

int main()
{
	int n,m;
	cin>>n>>m;
	rep(i,1,m)
		cin>>a[i];
	rep(i,1,n)
		rep(j,1,n)
			cin>>dis[i][j];
	rep(k,1,n)
		rep(i,1,n)
			rep(j,1,n)
				dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
	int ans=0;
	rep(i,2,m)
		ans+=dis[a[i-1]][a[i]];
	ans+=dis[1][a[1]];
    ans+=dis[a[m]][n];
    cout<<ans;
    return 0;
}